package com.hyb.weibo.user.service;

import com.hyb.weibo.common.enums.MessageEnum;
import com.hyb.weibo.common.service.BaseService;
import com.hyb.weibo.common.service.IBaseService;
import com.hyb.weibo.common.vo.JsonResult;
import com.hyb.weibo.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.common.BaseMapper;
import tk.mybatis.mapper.util.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;

@Service
public class UserServiceImpl extends BaseService<User> implements IBaseService<User> {

    @Autowired
    @Override
    public void setMapper(BaseMapper<User> mapper) {
        super.setMapper(mapper);
    }

    /**
     * 注册用户
     * @param user
     */
    public JsonResult regUser(User user) throws RuntimeException {
        if(StringUtil.isEmpty(user.getName())){
            return JsonResult.build(MessageEnum.USER_INPUT_USERNAME);
        }
        if(StringUtil.isEmpty(user.getPassword())){
            return JsonResult.build(MessageEnum.USER_INPUT_PASSWORD);
        }

        if(isExistWithName(user.getName())){
            return JsonResult.build(MessageEnum.REG_USER_EXIST);
        }else{
            insertSelective(user);
        }
        return JsonResult.ok(user,MessageEnum.REG_OK);
    }

    /**
     * 登录
     * @param user
     * @return
     */
    public JsonResult login(User user){
        if(StringUtil.isEmpty(user.getName())){
            return JsonResult.build(MessageEnum.USER_INPUT_USERNAME);
        }
        if(StringUtil.isEmpty(user.getPassword())){
            return JsonResult.build(MessageEnum.USER_INPUT_PASSWORD);
        }
        //检测用户是否存在
        if(!isExistWithName(user.getName())){
            return JsonResult.build(MessageEnum.LOGIN_USER_NOT_FOUND);
        }

        User checkUser = new User();
        checkUser.setName(user.getName());
        checkUser.setPassword(user.getPassword());
        User loginUser = findOne(checkUser);
        if(loginUser != null){
            return JsonResult.ok(loginUser,MessageEnum.LOGIN_OK);
        }else{
            return JsonResult.build(MessageEnum.LOGIN_PASSWORD_ERROR);
        }

    }

    /**
     * 根据用户名判断用户是否存在
     * @param userName
     * @return true-已存在 false-在不在
     */
    public boolean isExistWithName(String userName){
        User checkUser = new User();
        checkUser.setName(userName);
        User oldUser = findOne(checkUser);
        return oldUser != null;
    }

}
